package com.task.core.service.impl;

import java.util.List;

import javax.annotation.Resource;

import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Service;

import com.task.common.annotation.DataScope;
import com.task.common.domain.info.KeyAndValue;
import com.task.common.exception.ServiceException;
import com.task.common.utils.SecurityUtils;
import com.task.common.utils.uuid.UUID;
import com.task.core.domain.AdvertiserInfo;
import com.task.core.dto.request.AdvertiserRequestDTO;
import com.task.core.mapper.AdvertiserMapper;
import com.task.core.service.AdvertiserService;

/**
 * @author 迪迦.
 * @date 2024/10/30 13:34
 */
@Service("AdvertiserService")
public class AdvertiserServiceImpl implements AdvertiserService {

  @Resource
  private AdvertiserMapper advertiserMapper;

  @Override
  @DataScope(deptAlias = "dept", userAlias = "su")
  public List<AdvertiserInfo> getAdvertiserByPage(AdvertiserRequestDTO request) {
    //request.setOperationBy(SecurityUtils.checkAdmin());
    return advertiserMapper.getAdvertiserByPage(request);
  }

  @Override
  public AdvertiserInfo getBuyerByCodeOrName(String code, String name) {
    return advertiserMapper.getBuyerByCode(code, name);
  }

  @Override
  @DataScope(deptAlias = "dept", userAlias = "su")
  public List<KeyAndValue> getAdvertiserForOption(AdvertiserRequestDTO request) {
    //request.setOperationBy(SecurityUtils.checkAdmin());
    return advertiserMapper.getAdvertiserForOption(request);
  }

  @Override
  public void addAdvertiser(AdvertiserRequestDTO request) {
    request.setOperationBy(SecurityUtils.getLoginUser().getUserId());
    request.setCode(UUID.randomUUID().toString().replace("-", ""));
    advertiserMapper.addAdvertiser(request);
  }

  @Override
  @DataScope(deptAlias = "dept", userAlias = "su")
  public AdvertiserInfo getAdvertiserDetail(String advertiserCode) {
    AdvertiserRequestDTO advertiserRequestDTO = new AdvertiserRequestDTO();
    advertiserRequestDTO.setCode(advertiserCode);
    return advertiserMapper.getAdvertiserDetail(advertiserRequestDTO);
  }

  @Override
  public void modifyAdvertiser(AdvertiserRequestDTO request) {
    request.setOperationBy(SecurityUtils.getLoginUser().getUserId());
    Integer integer = advertiserMapper.modifyAdvertiser(request);
    if(integer == 0) {
      throw new ServiceException("code不存在");
    }
  }

  @Override
  public void deleteAdvertiser(String buyerCode, Long userId) {
    if (advertiserMapper.getUsedCount(buyerCode) > 0) {
      throw new ServiceException("有关联当前买家的任务,不允许删除");
    }
    Integer delete = advertiserMapper.deleteAdvertiser(buyerCode, userId);
    if(delete == 0) {
      throw new ServiceException("code不存在");
    }
  }
}
